import { useIntersectionObserver } from '@vueuse/core'
import imgError from '@/assets/image/imgError.svg'

export default function (app) {
  app.directive('img-lazy', {
    mounted(el, binding) {
      const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
        if (isIntersecting) {
          if (binding.value) {
            el.src = binding.value
            el.onload = function () {
              this.style.transform = 'none'
              if (!this.style.objectFit) {
                this.style.objectFit = 'cover'
              }
            }
            el.onerror = function () {
              this.style.transform = 'none'
              this.style.objectFit = 'contain'
              this.src = imgError
            }
            stop()
          }
        }
      })
    },
  })
}
